package net.caixiaomi.info.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.ArticleAdapter;
import net.caixiaomi.info.adapter.HomeGridAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.bgabanner.BGABanner;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.interfaces.SimpleEqualRatioTarget;
import net.caixiaomi.info.logger.Timber;
import net.caixiaomi.info.model.ArticleItem;
import net.caixiaomi.info.model.ArticlePageModel;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.HallModel;
import net.caixiaomi.info.model.HomeActivity;
import net.caixiaomi.info.model.HomeModel;
import net.caixiaomi.info.model.HomeNavBanners;
import net.caixiaomi.info.model.HomePlayClassifyItem;
import net.caixiaomi.info.model.HomeWinningMsgs;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.details.ArticleDetailActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.SchemeUtil;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import retrofit2.Call;

/**
 * 首页
 */

public class HomeFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, OnRefreshListener {
    public static final String TAG = "HomeFragment";

    @BindView(R.id.title)
    TextView mTitle;

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    private ViewFlipper mViewFlipper;
    private View mFlipperContainer;
    private View mPlayClassifyContainer;
    private BGABanner mBanner;
    private ImageView mAction;
    private RecyclerView mGridView;
    private HomeGridAdapter mGridViewAdapter;
    private ArticleAdapter mAdapter;
    private int mPageNum = 1;
    private HomeActivity mHomeActivity;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int fragmentLayout() {
        return R.layout.frag_home;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.app_name)).append(" · ").append(getString(R.string.bottom_home));
        mTitle.setText(stringBuilder.toString());
        mRefresh.setOnRefreshListener(this);
        initView();
        loadData();

    }

    private void initView() {
        try {
            View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_home, null);

            mBanner = (BGABanner) headerView.findViewById(R.id.banner);
            mBanner.setAdapter(new BGABanner.Adapter<ImageView, HomeNavBanners>() {
                @Override
                public void fillBannerItem(BGABanner banner, ImageView itemView, @Nullable HomeNavBanners model, int position) {
                    RequestOptions options = new RequestOptions().centerCrop();
                    int width = AppHelper.getScreenWidth(CommonApp.getInstance());
                    int height = (int) (AppHelper.getScreenWidth(CommonApp.getInstance()) / 2.8);
                    Glide.with(itemView.getContext()).asBitmap().apply(options).load(model.getBannerImage()).into(new SimpleEqualRatioTarget(itemView, width, height));
                }
            });
            mBanner.setDelegate(new BGABanner.Delegate<ImageView, HomeNavBanners>() {
                @Override
                public void onBannerItemClick(BGABanner banner, ImageView itemView, @Nullable HomeNavBanners model, int position) {
                    AppHelper.sendStatistics("banner", new String[]{"banner"}, new String[]{model.getBannerName()});
                    SchemeUtil.parseIntentUrl(itemView.getContext(), model.getBannerLink(),"banner-view");
                }
            });
            mBanner.setAspectRatio(2.8f);
            mFlipperContainer = headerView.findViewById(R.id.flipper_container);
            mViewFlipper = (ViewFlipper) headerView.findViewById(R.id.flipper);

            mAction = (ImageView) headerView.findViewById(R.id.action);
            mAction.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mHomeActivity != null) {
                        SchemeUtil.parseIntentUrl(v.getContext(), mHomeActivity.getActUrl(),"xinrenhuodong-view");
                    }
                }
            });
            ViewGroup.LayoutParams layoutParams = mAction.getLayoutParams();
            layoutParams.height = (int) (AppHelper.getScreenWidth(CommonApp.getInstance()) / 4.2);
            mAction.setLayoutParams(layoutParams);

            mPlayClassifyContainer = headerView.findViewById(R.id.content);
            mGridView = (RecyclerView) headerView.findViewById(R.id.grid);
            mGridView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
            mGridViewAdapter = new HomeGridAdapter(R.layout.item_home_grid);
            mGridViewAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    HomePlayClassifyItem homePlayClassifyItem = (HomePlayClassifyItem) adapter.getData().get(position);
                    if(TextUtils.equals(homePlayClassifyItem.getStatus(),"1")){
                        ToastUtil.s(homePlayClassifyItem.getStatusReason());
                        return;
                    }
                    AppHelper.sendStatistics("caizhongzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{homePlayClassifyItem.getLotteryName()});
                    SchemeUtil.parseIntentUrl(getActivity(), homePlayClassifyItem.getRedirectUrl(),"shijiebeipagepv");
                }
            });
            mGridView.setAdapter(mGridViewAdapter);

            mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
            mAdapter = new ArticleAdapter(null);
            mAdapter.setOnItemClickListener(this);
            mAdapter.setOnLoadMoreListener(this, mListView);
            mAdapter.addHeaderView(headerView);
            mAdapter.setEnableLoadMore(true);
            mListView.setAdapter(mAdapter);
            String text = CommonApp.STORE.getString(Constants.KEY_HOME_DATA);
            if (!TextUtils.isEmpty(text)) {
                mProgress.setVisibility(View.GONE);
                HomeModel homeModel = JSON.parseObject(text, HomeModel.class);
                bindDealData(homeModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadData() {
        boolean isTransaction = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
        JSONObject params = new JSONObject();
        params.put("page", mPageNum);
        params.put("size", Constants.PAGE_SIZE);
        params.put("isTransaction", isTransaction ? "2" : "1");
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<HomeModel>> home = requestService.getHallData(params);
        home.enqueue(new ResponseCallback<BaseCallModel<HomeModel>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<HomeModel> data) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                HomeModel homeModel = data.data;
                bindDealData(homeModel);
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;

            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;

            }
        });

    }

    private void bindDealData(HomeModel homeModel) {
        try {
            ArticlePageModel dlArticlePage = homeModel.getDlArticlePage();
            HallModel dlHallDTO = homeModel.getDlHallDTO();

            if (mPageNum == 1) {//只有第一页数据才更新banner
                String strData = JSON.toJSONString(homeModel);
                CommonApp.STORE.del(Constants.KEY_HOME_DATA);
                CommonApp.STORE.set(Constants.KEY_HOME_DATA, strData);

                List<HomeNavBanners> navBanners = dlHallDTO.getNavBanners();
                if (navBanners != null && !navBanners.isEmpty()) {
                    mBanner.setVisibility(View.VISIBLE);
                    mBanner.setData(R.layout.item_imageview, navBanners, null);
                    mBanner.setAutoPlayAble(navBanners.size() > 1);
                } else {
                    mBanner.setVisibility(View.GONE);
                }

                boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);

                List<HomeWinningMsgs> winningMsgs = dlHallDTO.getWinningMsgs();
                if (winningMsgs != null && !winningMsgs.isEmpty() && dealVersion) {
                    mViewFlipper.removeAllViews();
                    mFlipperContainer.setVisibility(View.VISIBLE);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int index = 0; index < winningMsgs.size(); index++) {
                        HomeWinningMsgs homeWinningMsgs = winningMsgs.get(index);
                        TextView textView = new TextView(getActivity());
                        textView.setPadding(0, (int) getResources().getDimension(R.dimen.padding_5), 0, (int) getResources().getDimension(R.dimen.padding_5));
                        textView.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), R.color.secondary_text));
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font_14));
                        stringBuilder.setLength(0);
                        stringBuilder.append(homeWinningMsgs.getWinningMsg()).append(homeWinningMsgs.getWinningMoney()).append(getResources().getString(R.string.C_MONEY));
                        SpannableString spannableString = new SpannableString(stringBuilder);
                        int start = stringBuilder.length() - 1 - homeWinningMsgs.getWinningMoney().length();
                        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), start, stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

                        textView.setText(spannableString);
                        mViewFlipper.addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    }
                    mViewFlipper.startFlipping();
                } else {
                    mFlipperContainer.setVisibility(View.GONE);
                }

                mHomeActivity = dlHallDTO.getActivity();
                if (mHomeActivity != null && dealVersion) {
                    mAction.setVisibility(View.VISIBLE);
                    int width = AppHelper.getScreenWidth(CommonApp.getInstance());
                    int height = (int) (AppHelper.getScreenWidth(CommonApp.getInstance()) / 4.2);
                    RequestOptions options = new RequestOptions().centerCrop();
                    Glide.with(this).asBitmap().apply(options).load(mHomeActivity.getActImg()).into(new SimpleEqualRatioTarget(mAction, width, height));
                } else {
                    mAction.setVisibility(View.GONE);
                }

                List<HomePlayClassifyItem> playClassifyItems = dlHallDTO.getDlPlayClassifyDetailDTOs();
                if (playClassifyItems != null && !playClassifyItems.isEmpty() && dealVersion) {
                    mPlayClassifyContainer.setVisibility(View.VISIBLE);
                    mGridViewAdapter.setNewData(playClassifyItems);
                } else {
                    mPlayClassifyContainer.setVisibility(View.GONE);
                }

            }

            List<ArticleItem> list = dlArticlePage.getList();
            if (list != null && !list.isEmpty()) {
                if (mPageNum == 1) {
                    mAdapter.getData().clear();
                }

                mAdapter.addData(list);
                mAdapter.loadMoreComplete();
                mAdapter.notifyDataSetChanged();
                mAdapter.setEnableLoadMore(Boolean.valueOf(dlArticlePage.getHasNextPage()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Timber.d("onHiddenChanged  = " + hidden);
        if (hidden) {
            mViewFlipper.stopFlipping();
            mBanner.stopAutoPlay();
        } else {
            mViewFlipper.startFlipping();
            mBanner.startAutoPlay();
        }
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        switch (event.getWhat()) {
            case EventWhat.EVENT_APP_BACKGROUND_UPDATE_DEAL_VERSION:
                onRefresh(mRefresh);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onPageStart(getActivity(), "dating-view");
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPageEnd(getActivity(), "dating-view");
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            ArticleItem item = (ArticleItem) adapter.getData().get(position);
            Intent intent = new Intent(getActivity(), ArticleDetailActivity.class);
            intent.putExtra("data", item.getArticleId());
            startActivity(intent);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        loadData();
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPageNum = 1;
        loadData();
    }
}
